<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">新建权限</el-button>

    <el-table
      stripe
      :data="permissionList"
      style="width: 100%; margin-top: 10px"
      border
    >
      <el-table-column align="center" label="权限编号">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="权限名称">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="权限说明">
        <template slot-scope="scope">{{
          scope.row.has_details.explain
        }}</template>
      </el-table-column>
      <el-table-column align="center" label="权限分类" width="220">
        <template slot-scope="scope">{{
          scope.row.classify_belongs_to_many[0].title
        }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        ref="pager"
        background
        :current-page.sync="pageIndex"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === '添加权限' ? '添加权限' : '编辑权限'"
    >
      <el-form :model="permission" label-width="80px" label-position="left">
        <el-form-item label="权限名称 *">
          <el-input v-model="permission.name" placeholder="请输入权限名称" />
        </el-form-item>

        <el-form-item label="权限说明 *">
          <el-input
            v-model="permission.instructions"
            placeholder="请输入权限说明"
          />
        </el-form-item>

        <el-form-item label="权限分类 *">
          <el-select
            v-model="permission.roles"
            placeholder="请选择类别"
            value-key="id"
          >
            <el-option
              v-for="item in classify"
              :key="item.id"
              :label="item.title"
              :value="item"
              :disabled="item.disabled == '1'"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SwitchRoles from './components/SwitchRoles'
import { getInfo } from '@/api/user'
import {
  getPermissions,
  deletePermissions,
  getPermissionsPage,
  insertPermissions,
  updatePermissions
} from '@/api/permissions'
import { getClassify } from '@/api/classify'

export default {
  name: 'PagePermission',
  components: { SwitchRoles },
  data() {
    return {
      permissionList: [], // 权限数据数组
      pageIndex: 1, // 第几页
      pageSize: 2, // 一页数量
      last_page: 0, // 最后一页
      currentIndex: 0, // 当前页数
      total: 0, // 总页数
      dialogVisible: false, // dialog显示隐藏
      dialogType: '', // dialog的标题
      userPermissions: '',
      permission: {
        name: '',
        instructions: '',
        roles: []
      }, // 权限
      classify: '', // 角色
      perId: '' // 编辑单个id 变量
    }
  },
  created() {
    this.selectPermissions()
    this.getUserInfo()
  },
  methods: {
    // 判断是否具有某某权限
    isPower(Permission) {
      for (let i = 0; i < this.userPermissions.length; i++) {
        if (this.userPermissions[i] == Permission) {
          return true
        }
      }
      return false
    },
    // 下一页
    sizeChangeHandle: function(size) {
      this.pagesize = size
    },
    currentChangeHandle: function(val) {
      this.currentIndex = val
      return new Promise((resolve, reject) => {
        getPermissionsPage(val).then((response) => {
          // 调用分页方法 下一页 查询
          this.permissionList = response.data.permissions.data
        })
      })
    },
    selectPermissions() {
      new Promise((reselve, reject) => {
        getPermissions().then((response) => {
          // 获取数据显示
          this.permissionList = response.data.permissions.data
          // 获取分页数据并设置
          this.total = response.data.permissions.total
          this.pageSize = response.data.permissions.to
          this.last_page = response.data.permissions.last_page
          // console.log(this.permissionList);
        })
      })
    },

    selectPage() {
      new Promise((reselve, reject) => {
        getPermissions().then((response) => {
          // 获取分页数据并设置
          this.total = response.data.permissions.total
          this.pageSize = response.data.permissions.to
          this.last_page = response.data.permissions.last_page
          // console.log(this.permissionList);
        })
      })
    },

    // 打开添加新的权限
    handleAddRole() {
      if (this.isPower('create power')) {
        this.dialogType = '添加权限'
        this.dialogVisible = true
        // 打开dialog框后查询角色内容 填充到select框中
        new Promise((resolve, reject) => {
          getClassify().then((response) => {
            // 填充数据
            // console.log(response.data);
            this.classify = response.data
          })
        })
      } else {
        this.$message({
          type: 'error',
          message: '没有添加权限,请联系管理员!'
        })
      }
    },

    // 提交dialog框
    confirmRole() {
      if (this.dialogType == '添加权限') {
        // 添加权限 请求
        new Promise((resolve, rejetc) => {
          insertPermissions({
            name: this.permission.name,
            instructions: this.permission.instructions,
            title: this.permission.roles.title,
            id: this.permission.roles.id
          }).then((response) => {
            this.$message({
              type: 'success',
              message: '权限添加成功'
            })
            // 添加权限成功后清除表单输入框内容
            this.permission.name = ''
            this.permission.instructions = ''
            this.permission.roles = ''
            // 关闭dialog框
            this.dialogVisible = false
            // this.selectPermissions();
            this.selectPage()
            const page =
              this.total % 8 == 0 ? this.last_page + 1 : this.last_page
            this.currentChangeHandle(page)
            this.pageIndex = page
          })
        })
      } else {
        // 编辑权限信息 请求
        new Promise((resolve, reject) => {
          updatePermissions({
            name: this.permission.name,
            instructions: this.permission.instructions,
            title: this.permission.roles.title,
            id: this.permission.roles.id,
            perId: this.perId
          }).then((response) => {
            this.$message({
              type: 'success',
              message: '修改权限成功'
            })
            // 添加权限成功后清除表单输入框内容
            this.permission.name = ''
            this.permission.instructions = ''
            this.permission.roles = ''
            // 关闭dialog框
            this.dialogVisible = false
            this.currentChangeHandle(this.currentIndex)
          })
        })
      }
    },
    // 取消dialog框
    cancelRole() {
      // 关闭dialog框
      this.dialogVisible = false
      // 取消弹框后 清除 表单内容
      this.permission.name = ''
      this.permission.instructions = ''
      this.permission.roles = ''
      this.classify = ''
      this.perId = ''
    },
    // 权限编辑
    handleEdit($index, row) {
      if (this.isPower('update power')) {
        this.dialogType = '编辑权限'
        this.dialogVisible = true
        // 将当前行的id 赋值给perId 后续修改传值id
        this.perId = row.id
        new Promise((resolve, reject) => {
          getClassify().then((response) => {
            this.classify = response.data
          })
        })
        this.permission.name = row.name
        this.permission.instructions = row.has_details.explain
        this.permission.roles = row.classify_belongs_to_many[0]
      } else {
        this.$message({
          type: 'error',
          message: '没有修改权限,请联系管理员!'
        })
      }
    },
    // 权限删除
    handleDelete($index, row) {
      if (this.isPower('delete power')) {
        this.$confirm('确认删除?', '警告', {
          configButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warring'
        })
          .then(() => {
            new Promise((resolve, reject) => {
              deletePermissions({ id: row.id }).then((response) => {
                this.selectPage()
                // console.log(this.total);
                const page =
                  this.total % 8 == 1 ? this.last_page - 1 : this.last_page
                // console.log(page);
                this.currentChangeHandle(page)
                this.pageIndex = page
                console.log('pahe' + this.pageIndex)
              })
            })
          })
          .catch(() => {})
      } else {
        this.$message({
          type: 'error',
          message: '没有删除权限,请联系管理员!'
        })
      }
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then((response) => {
          // console.log("info");
          // console.log(response.data);
          // this.username = response.data.name; //当前登录用户的姓名
          this.userPermissions = response.data.per // 当前登录用户权限数组
          // console.log(this.userPermissions);
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
